﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.IO.Pipes;
using System.Runtime.Remoting.Channels.Ipc;

namespace Kokomo.PeInspector.Profiler
{
	class Profiler
	{
		public static Profiler Start(string fileName, string arguments)
		{
			ProcessStartInfo startInfo = new ProcessStartInfo(fileName, arguments);
			Profiler profiler = new Profiler(startInfo);

			return profiler;
		}

		internal Profiler(ProcessStartInfo processStartInfo)
		{
			if (processStartInfo == null) throw new ArgumentNullException("processStartInfo");

			this.ProcessStartInfo = processStartInfo;
			this.Monitor = new ProfilerMonitor();
			this.Monitor.Register();

			//IpcChannel channel = new IpcChannel(

			Guid profilerStubGuid = new Guid("AEC185BC-AD7E-4358-A1C3-70D8915CE7A7");
			processStartInfo.EnvironmentVariables["COR_ENABLE_PROFILING"] = "1";
			processStartInfo.EnvironmentVariables["COR_PROFILER"] = "{" + profilerStubGuid.ToString() + "}";
			processStartInfo.EnvironmentVariables["KOKOMO_PROFILER_PORT"] = this.Monitor.PortName;
			processStartInfo.EnvironmentVariables["KOKOMO_PROFILER_URI"] = this.Monitor.InstanceUri;
			processStartInfo.UseShellExecute = false;

			Process process = Process.Start(processStartInfo);
			this.Process = process;
		}

		public ProcessStartInfo ProcessStartInfo { get; private set; }
		public Process Process { get; private set; }
		public ProfilerMonitor Monitor { get; private set; }
	}
}
